<template>
  <nut-wrapper>
    <view class="profile-container">
      <!-- 头像部分 -->
      <view class="avatar-section">
        <view class="avatar-wrapper">
          <nut-avatar size="large" @click="chooseAvatar">
            <img :src="userInfo.avatar"
          /></nut-avatar>
          <view class="change-avatar" @click="chooseAvatar">
            <i class="iconfont icon-camera"></i>
          </view>
        </view>
        <view class="nickname" @click="editNickname">
          {{ userInfo.nickname }}
          <i class="iconfont icon-edit"></i>
        </view>
      </view>

      <!-- 基本信息 -->
      <view class="section">
        <view class="section-title">
          <i class="iconfont icon-user"></i>
          <text>基本信息</text>
        </view>
        <nut-form>
          <nut-form-item label="性别">
            <nut-radio-group v-model="userInfo.gender" direction="horizontal">
              <nut-radio label="male">男</nut-radio>
              <nut-radio label="female">女</nut-radio>
            </nut-radio-group>
          </nut-form-item>

          <nut-form-item label="生日">
            <nut-date-picker
              v-model="userInfo.birthday"
              title="选择生日"
              :min-date="minDate"
              :max-date="maxDate"
              @confirm="onBirthdayConfirm"
            >
              <template #default>
                <view class="picker-value">
                  {{ userInfo.birthday || "请选择" }}
                </view>
              </template>
            </nut-date-picker>
          </nut-form-item>

          <nut-form-item label="地区">
            <nut-picker
              v-model="userInfo.region"
              :columns="regionColumns"
              title="选择地区"
              @confirm="onRegionConfirm"
            >
              <template #default>
                <view class="picker-value">
                  {{ userInfo.region.join(" ") || "请选择" }}
                </view>
              </template>
            </nut-picker>
          </nut-form-item>
        </nut-form>
      </view>

      <!-- 联系方式 -->
      <view class="section">
        <view class="section-title">
          <i class="iconfont icon-contact"></i>
          <text>联系方式</text>
        </view>
        <nut-form>
          <nut-form-item label="手机号">
            <nut-input
              v-model="userInfo.phone"
              placeholder="请输入手机号"
              type="tel"
            />
          </nut-form-item>

          <nut-form-item label="邮箱">
            <nut-input
              v-model="userInfo.email"
              placeholder="请输入邮箱"
              type="email"
            />
          </nut-form-item>
        </nut-form>
      </view>

      <!-- 保存按钮 -->
      <view class="submit-btn">
        <nut-button type="primary" block @click="saveProfile" :loading="saving">
          {{ saving ? "保存中..." : "保存" }}
        </nut-button>
      </view>
    </view>
  </nut-wrapper>
</template>

<script>
import Taro from "@tarojs/taro";
import { useUserStore } from "@/stores/userStore";
import {
  trackPageView,
  trackClick,
  trackFormSubmit,
  trackUserInfo,
} from "@/services/tracking";
import { handleValidationError } from "@/services/error";

export default {
  name: "Profile",
  data() {
    return {
      saving: false,
      minDate: new Date(1900, 0, 1),
      maxDate: new Date(),
      regionColumns: [
        ["北京", "上海", "广州", "深圳"],
        ["东城区", "西城区", "朝阳区", "海淀区"],
      ],
    };
  },
  computed: {
    userInfo() {
      return this.userStore.getUserInfo;
    },
  },
  setup() {
    const userStore = useUserStore();
    return { userStore };
  },
  mounted() {
    // 页面访问埋点
    trackPageView("/packageA/pages/profile/index", "个人资料");

    // 从本地存储加载用户信息
    this.userStore.loadFromStorage();
  },
  methods: {
    chooseAvatar() {
      Taro.chooseImage({
        count: 1,
        sizeType: ["compressed"],
        sourceType: ["album", "camera"],
        success: (res) => {
          this.userStore.updateUserField("avatar", res.tempFilePaths[0]);
        },
      });
    },
    editNickname() {
      Taro.showModal({
        title: "修改昵称",
        editable: true,
        placeholderText: "请输入新昵称",
        success: (res) => {
          if (res.confirm && res.content) {
            this.userStore.updateUserField("nickname", res.content);
          }
        },
      });
    },
    onBirthdayConfirm({ selectedValue }) {
      this.userStore.updateUserField("birthday", selectedValue.join("-"));
    },
    onRegionConfirm({ selectedValue }) {
      this.userStore.updateUserField("region", selectedValue);
    },
    async saveProfile() {
      this.saving = true;

      try {
        // 这里可以添加实际的保存逻辑，比如调用 API
        await new Promise((resolve) => setTimeout(resolve, 1000));

        // 保存到本地存储
        this.userStore.saveToStorage();

        Taro.showToast({
          title: "保存成功",
          icon: "success",
        });
      } catch (error) {
        Taro.showToast({
          title: "保存失败",
          icon: "error",
        });
      } finally {
        this.saving = false;
      }
    },
    showPasswordDialog() {
      trackClick("password_dialog", "修改密码");
      // ... 其他代码
    },
    showPhoneDialog() {
      trackClick("phone_dialog", "绑定手机号");
      // ... 其他代码
    },
    showEmailDialog() {
      trackClick("email_dialog", "绑定邮箱");
      // ... 其他代码
    },
    showDeleteAccountDialog() {
      trackClick("delete_account_dialog", "注销账号");
      // ... 其他代码
    },
    async updatePassword() {
      if (!this.validatePassword()) {
        handleValidationError({
          field: "password",
          message: "密码验证失败",
          value: this.passwordForm,
        });
        return;
      }

      try {
        trackFormSubmit("password_form", "修改密码", this.passwordForm);
        // ... 其他代码
      } catch (error) {
        handleError(error, "password_update_error");
      }
    },
    async updatePhone() {
      if (!this.validatePhone()) {
        handleValidationError({
          field: "phone",
          message: "手机号验证失败",
          value: this.phoneForm,
        });
        return;
      }

      try {
        trackFormSubmit("phone_form", "绑定手机号", this.phoneForm);
        // ... 其他代码
        trackUserInfo(this.userInfo);
      } catch (error) {
        handleError(error, "phone_update_error");
      }
    },
    async updateEmail() {
      if (!this.validateEmail()) {
        handleValidationError({
          field: "email",
          message: "邮箱验证失败",
          value: this.emailForm,
        });
        return;
      }

      try {
        trackFormSubmit("email_form", "绑定邮箱", this.emailForm);
        // ... 其他代码
        trackUserInfo(this.userInfo);
      } catch (error) {
        handleError(error, "email_update_error");
      }
    },
    async deleteAccount() {
      try {
        trackFormSubmit("delete_account", "注销账号");
        // ... 其他代码
      } catch (error) {
        handleError(error, "account_delete_error");
      }
    },
  },
};
</script>

<style lang="scss">
.profile-container {
  min-height: 100vh;
  background-color: #ffffff;
  padding-bottom: 40rpx;

  .avatar-section {
    padding: 40rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: #ffffff;
    margin-bottom: 20rpx;

    .avatar-wrapper {
      position: relative;
      margin-bottom: 20rpx;

      .change-avatar {
        position: absolute;
        right: -10rpx;
        bottom: -10rpx;
        width: 60rpx;
        height: 60rpx;
        background-color: $primary-color;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

        i {
          color: #fff;
          font-size: 32rpx;
        }
      }
    }

    .nickname {
      font-size: $font-size-2;
      color: $text-color;
      display: flex;
      align-items: center;
      gap: 10rpx;

      i {
        font-size: $font-size-1;
        color: $primary-color;
      }
    }
  }

  .section {
    margin: 30rpx;
    padding: 30rpx;
    background-color: #ffffff;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

    .section-title {
      display: flex;
      align-items: center;
      margin-bottom: 30rpx;
      font-size: $font-size-2;
      font-weight: bold;
      color: $text-color;

      i {
        margin-right: 10rpx;
        color: $primary-color;
        font-size: 40rpx;
      }
    }
  }

  .nut-form-item {
    margin-bottom: 30rpx;

    .nut-form-item__label {
      font-size: $font-size-1;
      color: $text-color;
      width: 160rpx;
    }

    .picker-value {
      font-size: $font-size-1;
      color: $text-color;
    }
  }

  .submit-btn {
    margin: 40rpx 30rpx;
  }

  // 深色模式样式
  [data-theme="dark"] {
    .profile-container {
      background-color: #000;
    }

    .avatar-section,
    .section {
      background-color: #000;
      box-shadow: none;
    }
  }
}
</style>
